package cn.fz.redisdemo01.web;

import cn.fz.redisdemo01.domain.dto.UserDto;
import cn.fz.redisdemo01.service.UserService;
import cn.fz.redisdemo01.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/redis")
public class BasicController {
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private UserService userService;

    // 保存数据
    @PostMapping("/save")
    public String save(@RequestParam("key") String key, @RequestParam("value") String value) {
        redisUtils.save(key, value);
        return "Data saved successfully!";
    }

    // 获取数据
    @GetMapping("/get")
    public Object get(@RequestParam("key") String key) {
        Object value = redisUtils.get(key);
        return value != null ? value : "Key not found";
    }

    // 删除数据
    @DeleteMapping("/delete")
    public String delete(@RequestParam("key") String key) {
        redisUtils.delete(key);
        return "Data deleted successfully!";
    }

    @GetMapping("/getAndSave")
    public UserDto getAndSave(@RequestParam("id") Long id) {
        return userService.getUserById(id);
    }

    @GetMapping("/updAndSave")
    public UserDto updAndSave(@RequestParam("id") Long id) {
        UserDto build = UserDto.builder().id(id).build();
        return userService.updateUser(build);
    }

    @GetMapping("/delUser")
    public String delUser(@RequestParam("id") Long id) {
        userService.deleteUser(id);
        return "Data deleted successfully!";
    }

    @GetMapping("/delAllUser")
    public String delAllUser() {
        userService.clearCache();
        return "Data deleted allUser successfully!";
    }
}
